/**
 * Created by xxx on 2017/7/12.
 */
'use strict';
import React, {
    Component
} from 'react'
import {
    Link,
    hashHistory
} from 'react-router'

import Header from './Common/Header'
import ConfirmBox from './Common/ConfirmBox'
import imgTest from '../Img/icon/add_img2.png'
import {
    HttpService,
    getLocalTime,
    Tips,
    imgUpload,
    AjaxUploadImg,
    viewerImg,
    showLoading,
    showHiding,
    taskFinish
} from '../Tools'

/*
 *班级相册-教师、家长
 */
export default class ScoreDetail extends Component {
    constructor(props) {
        super(props);
        this.imgfile = []; //多张图片
        this.publish = false;
        this.state = {
            isHaveImg: false,
            imgfiles: [] //图片对象数组
        }
    }

    componentDidMount() {
        if (this.props.params.content && this.props.params.content != 'undefined') {
            this.refs.photoremark.value = this.props.params.content;
        }
    }

    cfmCancel() {
        hashHistory.goBack(-1);
    }

    /**
     * 上传图片
     */
    addPhoto() {
        if (this.publish) {
            return;
        }
        const photoremark = this.refs.photoremark.value,
            bookid = this.props.params.id;
        // if (photoremark == '') {
        //     Tips('请填写照片描述');
        //     return;
        // }
        if (photoremark != '' && photoremark.length > 50) {
            Tips('照片描述最多50字');
            return;
        }
        let data = {
            jybTicket: sessionStorage.ticket,
            method: 'ajaxJybJSON_101AddPhotoToBook',
            bookid,
            photoremark
        };
        if (this.props.params.content) { //修改描述
            data.method = 'ajaxJybJSON_101AmendphotoRemark';
            data.photoid = this.props.params.photoid;
            this.postData(data);
        } else {
            if (this.state.imgfiles.length == 0) {
                Tips('请添加上传的图片');
                return;
            }
            this.publish = true;
            Tips('正在上传图片...', 0);
            let rct = this,
                fileId = '';
            // for(let i = 0;i<rct.state.imgfiles.length;i++){
            //     AjaxUploadImg(rct.state.imgfiles[i].msg, function(res) {
            //         if (res.status == 'ok') {
            //             fileId += res.msg+',';
            //             if(i == rct.state.imgfiles.length-1){
            //                 data.fileId = fileId.substring(0,fileId.length-1);
            //                 rct.postData(data);
            //             }
            //         } else {
            //             Tips(res.msg);
            //             rct.publish = false;
            //         }
            //     })
            // }
            showLoading(); //加载动画
            AjaxUploadImg(rct.state.imgfiles, function(res) {
                if (res.status == 'ok') {
                    data.fileId = res.msg;
                    rct.postData(data);
                } else {
                    showHiding(200); //加载动画
                    Tips(res.msg);
                    rct.publish = false;
                }
            })
        }
    }

    /**
     * 提交数据
     * @param data
     */
    postData(data) {
        HttpService.query({
            url: '/jxt-nyxt/ajaxClassPhotoBookDealer.do',
            data,
            async: false,
            success: (res => {
                setTimeout(() => {
                    this.publish = false;
                }, 400);
                showHiding(200); //加载动画
                if (res.code == 0) {
                    Tips('发布成功')
                    taskFinish('发布照片', (status, config) => {
                        if (status) {
                            this.config = config;
                            this.setState({
                                show: 1
                            })
                        } else {
                            hashHistory.goBack(-1);
                        }
                    })
                    return;
                }
                Tips('发布失败');
            })
        })
    }

    sigleImg(inputId, imgId, files, len, i) {

        let rct = this,
            reader = new FileReader(),
            src = '';
        reader.readAsDataURL(files[i]);
        reader.onload = function() {
            src = this.result;
        };
        imgUpload({
            inputId,
            imgId,
            imgIeId: imgId,
            index: i
        }, function(status, msg) {
            showLoading(); //加载动画
            if (status) {
                //组装图片数据
                rct.state.imgfiles.push({
                    msg: msg,
                    src: src
                });
                rct.setState({
                    isHaveImg: true,
                    imgfiles: rct.state.imgfiles
                });
                i++;
                //console.log(files);
                if (i < len) {
                    rct.sigleImg(inputId, imgId, files, len, i)
                } else {
                    document.querySelector('#upcard').value = '';
                    showHiding(200); //关闭动画
                    Tips('关闭')
                }
            } else {
                Tips(msg);
            }
        });
    }

    /**
     * 添加图片
     * @param inputId
     * @param imgId
     */
    upLoadImg(inputId, imgId) {
        let rct = this,
            files = document.querySelector('#' + inputId + '').files;
        let len = files.length;
        if (rct.state.imgfiles.length + files.length > 9) {
            Tips('最多能上传9张图片');
            len = 9 - rct.state.imgfiles.length;
        } else {
            Tips('正在添加图片..')
        }
        rct.files = files;
        rct.sigleImg(inputId, imgId, files, len, 0)
    }
    /**
     * 清理上传的图片
     * @param e
     */
    upImgClean(index, e) {
        e.preventDefault();
        let array = [];
        for (let i = 0; i < this.state.imgfiles.length; i++) {
            if (i != index) {
                array.push(this.state.imgfiles[i]);
            }
        }
        this.setState({
            isHaveImg: false,
            imgfiles: array
        });
    }

    render() {
        const {
            photoid,
            content
        } = this.props.params;
        let imgs = this.state.imgfiles.map((data, index) => {
            return (
                <label className='lineblock'>
                    {/* 苹果手机照相会倒 style={{backgroundImage:"url("+data.src+")"}}*/}
                    <div >
                        <span className="close" onClick={this.upImgClean.bind(this,index)}/>
                        <img src={data.src} style={{opacity:'1'}} onClick={viewerImg.bind(this, 'src')}/>
                    </div>
                </label>
            )
        });
        const publishLink = <a className='h_link color_blue' onClick={this.addPhoto.bind(this)}>发布</a>;
        return (
            <div className='add_photo'>
                <Header title={photoid
                    ? '编辑照片描述'
                    : '上传照片'} link={publishLink}/>
                <div className="centent">
                    <div className="input_value">
                        <textarea ref='photoremark' placeholder="请输入照片描述（最多50个字）"/>
                    </div>
                    {
                        photoid ? '' :
                            <div className="img" id="imgList" style={{paddingBottom:'2rem'}}>
                                {imgs}
                                <label className='lineblock' style={{display: this.state.imgfiles.length==9?'none':'block'}}>
                                    <img src={imgTest} id='upimg' style={{display: 'none'}}/>
                                    <img src={imgTest} className='upViewerImg' style={{display: 'block'}} />
                                    <input className='upcard hidden' name='front' type="file" id="upcard" accept="image/gif,image/jpeg,image/jpg,image/png"  onChange={this.upLoadImg.bind(this, 'upcard', 'upimg')} multiple='multiple' />
                                    {/*multiple='multiple'*/}
                                </label>
                            </div>
                    }
                </div>
                <ConfirmBox config={this.config} show={this.state.show} cancel={this.cfmCancel.bind(this)}/>
            </div>
        )
    }
}
